﻿using System;

public class Mapper007 : MapperDefault
{
    internal int currentMirroring;
    internal int currentOffset;
    internal short[] prgrom;

    public override void init(NES nes)
    {
        base.init(nes);
        this.currentOffset = 0;
        this.currentMirroring = -1;
        ROM rom = nes.Rom;
        int romBankCount = rom.RomBankCount;
        this.prgrom = new short[romBankCount * 0x4000];
        for (int i = 0; i < romBankCount; i++)
        {
            Array.Copy(rom.getRomBank(i), 0, this.prgrom, i * 0x4000, 0x4000);
        }
    }

    public override short load(int address)
    {
        if (address < 0x8000)
        {
            return base.load(address);
        }
        if ((address + this.currentOffset) >= 0x40000)
        {
            return this.prgrom[(address + this.currentOffset) - 0x40000];
        }
        return this.prgrom[address + this.currentOffset];
    }

    public override void mapperInternalStateLoad(ByteBuffer buf)
    {
        base.mapperInternalStateLoad(buf);
        if (buf.readByte() == 1)
        {
            this.currentMirroring = buf.readByte();
            this.currentOffset = buf.readInt();
        }
    }

    public override void mapperInternalStateSave(ByteBuffer buf)
    {
        base.mapperInternalStateSave(buf);
        buf.putByte(1);
        buf.putByte((short) this.currentMirroring);
        buf.putInt(this.currentOffset);
    }

    public override void reset()
    {
        base.reset();
        this.currentOffset = 0;
        this.currentMirroring = -1;
    }

    public override void write(int address, short value_Renamed)
    {
        if (address < 0x8000)
        {
            base.write(address, value_Renamed);
        }
        else
        {
            this.currentOffset = ((value_Renamed & 15) - 1) << 15;
            if (this.currentMirroring != (value_Renamed & 0x10))
            {
                this.currentMirroring = value_Renamed & 0x10;
                if (this.currentMirroring == 0)
                {
                    base.nes.Ppu.Mirroring = 3;
                }
                else
                {
                    base.nes.Ppu.Mirroring = 4;
                }
            }
        }
    }
}

